package com.gnerv.cms.aspect;

import com.gnerv.cms.entity.StatisticsApi;
import com.gnerv.cms.service.IStatisticsApiService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Aspect
@Component
public class StatisticsApiAspect {

    @Resource
    private IStatisticsApiService statisticsApiService;

    @Pointcut("execution(public * com.gnerv.cms.controller..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        if("GET".equals(method)){
            Object[] args = joinPoint.getArgs();
            for (Object arg : args) {
                if(arg instanceof String){
                    requestURI = requestURI.replaceAll(String.valueOf(arg), "");
                }
            }
        }
        statisticsApiService.insertOrUpdateStatisticsApi(new StatisticsApi(requestURI, 0));
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        log.info("RESPONSE : " + ret);
    }


}

